<?php

namespace addons\helper\controller\wxapp\auth;

use addons\helper\controller\wxapp\Base;
use fast\Random;
use fast\Tree;
use think\Validate;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;

class Admin extends Base
{
    protected $searchFields = 'id,username';
    protected $config = [
        'model'             => '管理员',
        'limit'             => 10,
        'defaultSort'       => 'id',
        'defaultOrder'      => 'desc',
        'tabField'          => '',
        'searchPlaceholder' => '输入ID或用户名搜索',
        'multi'             => true,
        'search'            => true,
        'field' => [
            'groups'       => ['所属组别', 'selects', false,  false, '', true, true, true],
            'username'     => ['用户名', 'text', false,  false, '', true, true, true],
            'nickname'     => ['昵称', 'text', false,  false, '', true, true, true],
            'password'     => ['密码', 'password', false,  false, '', false, true, true],
            'avatar'       => ['头像', 'image', false,  false, '', true, true, true],
            'email'        => ['电子邮箱', 'text', false,  false, '', true, true, true],
            'mobile'       => ['手机号码', 'number', false,  false, '', true, true, true],
            'loginfailure' => ['失败次数', 'number', false,  false, '', true, true, false],
            'logintime'    => ['最后登录', 'datetime', false, false, '', true, false, false],
            'loginip'      => ['登录IP', 'text', false, false, '', true, false, false],
            'createtime'   => ['创建时间', 'datetime', false, false, '', true, false, false],
            'updatetime'   => ['更新时间', 'datetime', false, false, '', true, false, false],
            'status'       => ['状态', 'select', false, false, '', true, true, true],
        ],
        'fieldContent' => [
            'groups' => [],
            'status' => [
                'normal' => '正常',
                'hidden' => '隐藏'
            ]
        ],
        // [可选]前端表单验证规则
        'rules' => [
            'groups' => [
                'required'    => true
            ],
            'username' => [
                'required'    => true,
                'username'    => true
            ],
            'nickname' => [
                'required'    => true
            ],
            'password' => [
                'required'    => 'add',
                'password'    => true
            ],
            'email' => [
                'required'    => true,
                'email'       => true
            ]
        ],
        'auth' => [
            'add'  => [
                'name' => '添加',
                'url'  => 'auth.admin/add',
            ],
            'edit'  => [
                'name' => '编辑',
                'url'  => 'auth.admin/edit',
            ],
            'multi' => [
                'del'  => [
                    'name'        => '删除',
                    'color'       => '#e74c3c',
                    'icon'        => 'fa-trash',
                    'url'         => 'auth.admin/del'
                ]
            ],
            'more' => [
                'del'  => [
                    'name'  => '删除',
                    'color' => '#e74c3c',
                    'url'   => 'auth.admin/del'
                ],
            ],
        ],
    ];

    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Admin;
        $this->config['field'] = $this->formatField();
        $this->config['pk'] = $this->model->getPk() ? $this->model->getPk() : 'id';

        $this->childrenAdminIds = $this->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList, null, '　');
        $groupdata = [];
        if ($this->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[] = [
                    $v['id'] => $v['name']
                ];
            }
        } else {
            $result = [];
            $groups = $this->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                foreach ($childlist as $k => $v) {
                    $result[] = [
                        $v['id'] => $v['name']
                    ];
                }
            }
            $groupdata = $result;
        }
        $this->config['fieldContent']['groups'] = $groupdata;
    }
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $childrenGroupIds = $this->childrenGroupIds;
            $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
                ->column('id,name');
            $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                ->field('uid,group_id')
                ->select();

            $adminGroupName = [];
            foreach ($authGroupList as $k => $v) {
                if (isset($groupName[$v['group_id']])) {
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
                }
            }
            $groups = $this->getGroups();
            foreach ($groups as $m => $n) {
                $adminGroupName[$this->userId][$n['id']] = $n['name'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('id', 'in', $this->childrenAdminIds)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('id', 'in', $this->childrenAdminIds)
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => &$v) {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $v['groups'] = implode(',', array_keys($groups));
                $tmp = array_values($groups);
                foreach ($tmp as &$t) {
                    $t = __($t);
                }
                $v['groups_text'] = implode(',', $tmp);
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            $data = [
                'tabList'  => null,
                'dataList' => $result,
                'config'   => $this->config
            ];
            $this->success('ok', $data);
        }
    }
    public function edit()
    {
        $ids = $this->request->get('ids');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!in_array($row->id, $this->childrenAdminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if ($params['password']) {
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('app\admin\validate\Admin');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,12}|unique:admin,username,' . $row->id,
                    'email'    => 'require|email|unique:admin,email,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('app\admin\validate\Admin.edit')->allowField(true)->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('app\admin\model\AuthGroupAccess')->where('uid', $row->id)->delete();

                $group = $this->request->post('groups');
                $group = explode(',', $group);
                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('app\admin\model\AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        unset($row['password'], $row['salt'], $row['token']);
        $row['groups'] = implode(',', $groupids);
        $this->success('ok', $row);
    }
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if (!Validate::is($params['password'], '\S{6,16}')) {
                    $this->error(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = $params['avatar'] ?: '/assets/img/avatar1.png'; //设置新管理员默认头像。
                $result = $this->model->validate('app\admin\validate\Admin.add')->allowField(true)->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $group = $this->request->post('groups');
                $group = explode(',', $group);

                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('app\admin\model\AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
    }
    public function del()
    {
        $ids = $this->request->post('ids/a');
        if ($ids) {
            $ids = array_intersect($this->childrenAdminIds, array_filter($ids));
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
                $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_values(array_diff($deleteIds, [$this->userId]));
                if ($deleteIds) {
                    $this->model->destroy($deleteIds);
                    model('app\admin\model\AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error(__('You have no permission'));
    }
}
